package com.xgj.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpUtil {

    // 默认超时时间（毫秒）
    private static final int DEFAULT_CONNECT_TIMEOUT = 5000;
    private static final int DEFAULT_READ_TIMEOUT = 10000;

    /**
     * 发送 GET 请求
     * @param urlString 请求地址（含参数）
     * @param headers   请求头（可空）
     */
    public static String get(String urlString, Map<String, String> headers) throws Exception {
        return sendRequest(urlString, "GET", headers, null);
    }

    /**
     * 发送 POST 请求
     * @param urlString 请求地址
     * @param headers   请求头（可空）
     * @param body      请求体（可空）
     */
    public static String post(String urlString, Map<String, String> headers, String body) throws Exception {
        return sendRequest(urlString, "POST", headers, body);
    }

    /**
     * 通用 HTTP 请求方法
     * @param method    HTTP 方法（GET/POST/PUT/DELETE）
     * @param headers   请求头
     * @param body      请求体（POST/PUT 时使用）
     */
    private static String sendRequest(String urlString, String method, Map<String, String> headers, String body) throws Exception {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();

            // 基础配置
            connection.setRequestMethod(method.toUpperCase());
            connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            connection.setReadTimeout(DEFAULT_READ_TIMEOUT);
            connection.setUseCaches(false);

            // 设置请求头
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            // 处理请求体（POST/PUT）
            if (isBodyAllowed(method) && body != null && !body.isEmpty()) {
                connection.setDoOutput(true);
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = body.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }
            }

            // 处理响应
            int statusCode = connection.getResponseCode();
            if (statusCode >= 200 && statusCode < 300) {
                return readResponse(connection.getInputStream());
            } else {
                String errorResponse = readResponse(connection.getErrorStream());
                throw new RuntimeException("HTTP Error: " + statusCode + ", Response: " + errorResponse);
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    // 判断是否允许有请求体
    private static boolean isBodyAllowed(String method) {
        return "POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method);
    }

    // 读取响应内容
    private static String readResponse(InputStream inputStream) throws Exception {
        if (inputStream == null) return "";
        try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        }
    }

    // 测试全量接口
    public static void main(String[] args) {
        try {
            String response = get("https://randomuser.me/api/?results=5000", null);
            System.out.println("响应长度: " + response.length());
            // 此处可替换为 JSON 解析逻辑
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
